<?php

/**
 * 
 * ClientEngage: ClientEngage Visitor Voice (http://www.clientengage.com)
 * Copyright 2012, ClientEngage (http://www.clientengage.com)
 *
 * You must have purchased a valid license from CodeCanyon in order to have 
 * the permission to use this file.
 * 
 * You may only use this file according to the respective licensing terms 
 * you agreed to when purchasing this item on CodeCanyon.
 * 
 * 
 * 
 *
 * @author          ClientEngage <contact@clientengage.com>
 * @copyright       Copyright 2013, ClientEngage (http://www.clientengage.com)
 * @link            http://www.clientengage.com ClientEngage
 * @since           ClientEngage - Visitor Voice v 1.0
 * 
 */

/**
 * Layout helper
 */
class CustomformHelper extends AppHelper
{

    public $helpers = array(
        'Html' => array('className' => 'AppHtml'),
        'Text',
        'Time' => array('className' => 'AppTime'),
        'Number' => array('className' => 'AppNumber'),
        'Form' => array('className' => 'AppForm'));

    function __construct(View $view, $settings = array())
    {
        parent::__construct($view, $settings);
    }

    public function renderField($field = array(), $readOnly = false)
    {
        if (empty($field))
            return null;

        if (isset($field['Field']['id']))
        {
            foreach ($field['Field'] as $k => $v)
                $field[$k] = $v;

            unset($field['Field']);
        }


        if (method_exists($this, 'render_' . $field['type']))
            return call_user_method('render_' . $field['type'], $this, $field, $readOnly);
        else
            return null;
    }

    public function render_textshort($field = array(), $readOnly = false)
    {
        $options = array(
            'type' => 'text',
            'class' => $field['class_suffix_input'],
            'between' => '<div class="input-container">',
            'after' => '</div>',
            'placeholder' => $field['placeholder'],
            'div' => 'input control-group text ' . $field['class_suffix_container']);
        $fN = $this->__getFieldName();
        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_textlong($field = array(), $readOnly = false)
    {
        $options = array(
            'type' => 'textarea',
            'class' => $field['class_suffix_input'],
            'between' => '<div class="input-container">',
            'after' => '</div>',
            'placeholder' => $field['placeholder'],
            'div' => 'input control-group textarea ' . $field['class_suffix_container']);
        $fN = $this->__getFieldName();
        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_select($field = array(), $readOnly = false)
    {
        $fieldOptions = array('' => __('Please select')) + Hash::combine($field, 'FieldOption.{n}.id', 'FieldOption.{n}.title');

        $options = array(
            'type' => 'select',
            'options' => $fieldOptions,
            'class' => $field['class_suffix_input'],
            'between' => '<div class="input-container">',
            'after' => '</div>',
            'div' => 'input control-group select ' . $field['class_suffix_container']);
        $fN = $this->__getFieldName();
        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'field_option_id', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_selectmultiple($field = array(), $readOnly = false)
    {
        $fieldOptions = Hash::combine($field, 'FieldOption.{n}.id', 'FieldOption.{n}.title');

        $options = array(
            'type' => 'select',
            'options' => $fieldOptions,
            'multiple' => true,
            'class' => $field['class_suffix_input'],
            'between' => '<div class="input-container">',
            'after' => '</div>',
            'div' => 'input control-group select ' . $field['class_suffix_container']);
        $fN = $this->__getFieldName();
        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'FieldOption', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_radio($field = array(), $readOnly = false)
    {
        $fieldOptions = Hash::combine($field, 'FieldOption.{n}.id', 'FieldOption.{n}.title');
        $required = $field['required'] ? ' <span class="required">*</span>' : '';

        $label = '<label>' . $field['title'] . $required . ($field['description'] != '' ? '<small class="label-description">' . $field['description'] . '</small>' : '') . '</label>';
        $options = array(
            'type' => 'radio',
            'class' => $field['class_suffix_input'] . ' required',
            'options' => $fieldOptions, 'legend' => false,
            'fieldset' => false,
            'before' => $label . '<div class="input-container radio">',
            'after' => '</div>',
            'div' => 'input control-group radiogroup ' . $field['class_suffix_container']);

        $fN = $this->__getFieldName();
        $OPT = Hash::merge($this->__generateFieldOptions($field), $options);
        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'field_option_id', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_checkbox($field = array(), $readOnly = false)
    {
        $options = array(
            'type' => 'checkbox',
            'class' => $field['class_suffix_input'],
            'before' => '<div class="input-container checkbox">',
            'after' => '</div>',
            'div' => 'input control-group single_checkbox ' . $field['class_suffix_container']);
        $fN = $this->__getFieldName();
        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_checkboxmultiple($field = array(), $readOnly = false)
    {
        $fieldOptions = Hash::combine($field, 'FieldOption.{n}.id', 'FieldOption.{n}.title');
        $fN = $this->__getFieldName();

        $requiredClass = '';
        if ($field['required'] === true)
            $requiredClass = 'required';

        $options = array(
            'multiple' => 'checkbox',
            'class' => 'checkbox ' . $field['class_suffix_input'],
            'options' => $fieldOptions,
            'between' => '<div class="input-container"' . (($field['required'] === true) ? ' data-error-message="' . htmlspecialchars($field['required_message']) . '"' : '') . '>',
            'after' => '</div>',
            'div' => 'input control-group checkbox_multiple ' . $field['class_suffix_container'] . ' ' . $requiredClass);

        return $this->__getMetaFields($fN, $field) . $this->input($fN . 'FieldOption', Hash::merge($this->__generateFieldOptions($field), $options));
    }

    public function render_rating($field = array(), $readOnly = false)
    {
        $fN = $this->__getFieldName();
        $options = array(
            'class' => self::$fieldIndex . '_raty_input',
            'div' => 'input control-group rating ' . $field['class_suffix_container'],
            'type' => 'text',
            'between' => '<div class="input-container">',
            'after' => '<div class="' . self::$fieldIndex . '_raty"></div></div>',
            'style' => 'display: none;');

        $curVal = $this->Form->value($fN . 'value') != null ? (' score: ' . $this->Form->value($fN . 'value') . ',') : '';
        $this->Form->unlockField('score');
        $html = $this->Html->script('raty/jquery.raty.min', array('inline' => true));
        $html .= $this->Html->scriptBlock("
$(function(){
    $('." . self::$fieldIndex . "_raty').raty({
        " . $curVal . " 
        click: function(score, evt){ 
            $('." . self::$fieldIndex . "_raty_input').val(score); 
            if('valid' in $('." . self::$fieldIndex . "_raty_input'))
                $('." . self::$fieldIndex . "_raty_input').valid();   
        }, 
        path: '" . $this->Html->getWebroot() . "js/raty/img/',
        hints: false,
        number: " . $field['custom_max'] . ",
        size: 25,
        " . ($readOnly ? 'readOnly: true,' : '') . "
        starHalf   : 'star-half-big.png',
        starOff    : 'star-off-big.png',
        starOn     : 'star-on-big.png'            
    });
});            
", array('inline' => true));

        $html .= $this->Form->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));

        return $this->__getMetaFields($fN, $field) . $html;
    }

    public function render_slider($field = array(), $readOnly = false)
    {
        $fN = $this->__getFieldName();
        $options = array(
            'class' => self::$fieldIndex . '_ui-slider-val',
            'div' => 'input control-group slider ' . $field['class_suffix_container'],
            'between' => '<div class="input-container"><span class="slider_value" style="float:left">' . $this->Form->value($fN . 'value') . '</span><div style="margin-left: 25px;" class="' . self::$fieldIndex . '_slider_input' . '"></div><div style="clear:both"></div>',
            'after' => '</div>',
            'type' => 'text',
            'style' => 'display: none;'
        );

        $html = $this->Html->css('/js/jquery/jqueryui/css/smoothness/smoothness.min.css?1', null, array('inline' => true));
        $html .= $this->Html->script('jquery/jqueryui/js/jquery-ui.min', array('inline' => true));
        $html .= $this->Html->scriptBlock("
$(function(){
    $('." . self::$fieldIndex . "_slider_input').slider({
        min: " . $field['custom_min'] . ",
        max: " . $field['custom_max'] . ",
        " . ($readOnly ? 'disabled: true,' : '') . "
        " . (is_numeric($this->Form->value($fN . 'value')) ? ('value: ' . $this->Form->value($fN . 'value') . ',') : '') . "
        slide: function( event, ui ) {
            $(this).parent().children('span.slider_value').html(ui.value);
            $('." . self::$fieldIndex . '_ui-slider-val' . "').val(ui.value);
            if('valid' in $('." . self::$fieldIndex . '_ui-slider-val' . "'))
                $('." . self::$fieldIndex . '_ui-slider-val' . "').valid();
        }
    });

});            
", array('inline' => true));
        $html .= $this->Form->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));

        return $this->__getMetaFields($fN, $field) . $html;
    }

    public function render_spinner($field = array(), $readOnly = false)
    {
        $fN = $this->__getFieldName();
        $options = array(
            'class' => self::$fieldIndex . '_spinner_input ' . $field['class_suffix_input'],
            'div' => 'input control-group spinner ' . $field['class_suffix_container'],
            'type' => 'text',
            'between' => '<div class="input-container">', 'after' => '</div>',
            'placeholder' => $field['placeholder']
        );
        $html = $this->Html->css('/js/jquery/jqueryui/css/smoothness/smoothness.min.css?1', null, array('inline' => true));
        $html .= $this->Html->script('jquery/jqueryui/js/jquery-ui.min', array('inline' => true));
        $html .= $this->Html->scriptBlock("
$(function(){
    $('." . self::$fieldIndex . "_spinner_input').spinner({
        min: " . $field['custom_min'] . ",
        max: " . $field['custom_max'] . ",
        " . ($readOnly ? 'disabled: true,' : '') . "
        spin: function(){
            if('valid' in $('." . self::$fieldIndex . "_spinner_input'))
                $('." . self::$fieldIndex . "_spinner_input').valid();
        },
        change: function(){
            if('valid' in $('." . self::$fieldIndex . "_spinner_input'))
                $('." . self::$fieldIndex . "_spinner_input').valid();
        },
    });
    
    $('." . self::$fieldIndex . "_spinner_input').keyup(function () { 
        this.value = this.value.replace(/[^0-9\.]/g,'');
    });

});            
", array('inline' => true));
        $html .= $this->Form->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));

        return $this->__getMetaFields($fN, $field) . $html;
    }

    public function render_date($field = array(), $readOnly = false)
    {
        $fN = $this->__getFieldName();
        $options = array(
            'class' => self::$fieldIndex . '_date_input ' . $field['class_suffix_input'],
            'div' => 'input control-group date ' . $field['class_suffix_container'],
            'type' => 'text',
            'between' => '<div class="input-container">', 'after' => '</div>',
            'placeholder' => $field['placeholder']
        );
        $html = $this->Html->css('/js/jquery/jqueryui/css/smoothness/smoothness.min.css?1', null, array('inline' => true));
        $html .= $this->Html->script('jquery/jqueryui/js/jquery-ui.min', array('inline' => true));
        $html .= $this->Html->scriptBlock("
$(function(){
    $('." . self::$fieldIndex . "_date_input').datepicker();
    $('." . self::$fieldIndex . "_date_input').change(function(){
        if('valid' in $(this))
            $(this).valid();
    });
});            
", array('inline' => true));
        $html .= $this->Form->input($fN . 'value', Hash::merge($this->__generateFieldOptions($field), $options));

        return $this->__getMetaFields($fN, $field) . $html;
    }

    public function render_htmlspacer($field = array(), $readOnly = false)
    {
        return '<div class="htmlspacer">' . $field['description'] . '</div>';
    }

    private static $fieldIndex = 0;

    private function __getFieldName()
    {
        return 'Response.' . self::$fieldIndex++ . '.';
    }

    private function __getMetaFields($name, $field = array())
    {
        return $this->Form->hidden($name . 'field_id', array('value' => $field['id']));
    }

    private function __generateFieldOptions($field)
    {
        $required = $field['required'] ? ' <span class="required">*</span>' : '';
        $options = array('label' => $field['title'] . $required . ($field['description'] != '' ? '<small class="label-description">' . $field['description'] . '</small>' : ''));

        if ($field['required'] === true)
        {
            $options['required'] = true;
            $options['data-error-message'] = htmlspecialchars($field['required_message']);
        }

        return $options;
    }

    public function create($model = null, $options = array())
    {
        $defaults = array();
        $options = Set::merge($defaults, $options);

        return $this->Form->create($model, $options);
    }

    public function end($btn = null)
    {
        return $this->Form->end($btn);
    }

    public function input($model = null, $options = array())
    {
        $defaults = array();
        $options = Set::merge($defaults, $options);

        return $this->Form->input($model, $options);
    }

    public function render_captcha($field)
    {
        $img = $this->Html->image(Router::url(array('controller' => 'visitorforms', 'action' => 'simage', 'admin' => false), true), array('id' => 'captcha', 'class' => 'captcha-image'));
        $reloadLink = '<a class="reloadlink" href="#" onclick="document.getElementById(\'captcha\').src = \'' . Router::url(array('controller' => 'visitorforms', 'action' => 'simage', 'admin' => false), true) . '/\' + Math.random(); return false">' . __('Reload') . '</a>';

        $html = '';
        $options = array(
            'label' => $field['title'] . '<span class="required">*</span>' . ($field['description'] != '' ? '<small class="label-description">' . $field['description'] . '</small>' : ''),
            'class' => $field['class_suffix_input'],
            'div' => 'input control-group captcha ' . $field['class_suffix_container'],
            'type' => 'text',
            'between' => '<div class="input-container">' . $img . $reloadLink,
            'after' => '</div>',
            'data-error-message' => htmlspecialchars($field['required_message']),
            'required' => true,
        );

        $html .= $this->Form->input('captcha', $options);

        return $html;
    }

    public function render_submit($field)
    {
        return $this->Form->submit($field['title'], array('class' => $field['class_suffix_input'], 'div' => $field['class_suffix_container']));
    }

}